package com.bit.demo16.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {
    private Socket socket;
    public EchoClient(String serverIp,int serverPort) throws IOException {
        // 在 new 这个对象的时候就涉及到 "建立连接操作"
        // 由于连接建立好了之后, 服务器的信息就在操作系统中被 TCP 协议记录了.
        // 我们在应用程序层面上就不需要保存 IP 和 端口.
        socket = new Socket(serverIp, serverPort);
    }
    public void start(){
        System.out.println("client start");
        Scanner scanner=new Scanner(System.in);
        //分别获取从服务器发来的数据流和向服务器发送的数据流
        try (InputStream inputStream=socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream()){
            Scanner inputScanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while  (true){
                //从控制台读取用户的输入
                System.out.print(">");
                String request=scanner.nextLine();
                //构造请求发送给服务器
                writer.println(request);
                //刷新缓冲区
                writer.flush();
                //读取服务器的响应
                if (!inputScanner.hasNext()){
                    System.out.println("server discount");
                    break;
                }
                String response=inputScanner.next();
                System.out.println("server response:"+response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient client = new EchoClient("127.0.0.1",9090);
        client.start();
    }
}
